/**
 * Created by yihua on 2017/3/6.
 */

$(document).ready(function () {
    init();
    $("#add_confirm").unbind('click').click(function () {
        //$("#deleteModal").modal("hide");
        var options = {
            url: '/home/management/adddashanggift',
            beforeSubmit: validate,  // pre-submit callback
            success: showResponse,  // post-submit callback
            dataType: 'json',
            type: 'get',
            data: {}
        };
        $("#addForm").ajaxSubmit(options);
    });
    function validate(formData) {
        for (var i = 0; i < formData.length; i++) {
            if ('file' == formData[i].name) {
                break;
            }
            if (!formData[i].value) {
                console.log(formData[i].name)
                toastr.error('请输入所有选项', '', {positionClass: 'toast-bottom-center'});
                return false;
            }
        }
    }

    function showResponse(responseText) {

        if (0 !== responseText.errno) {
            toastr.error(responseText.errmsg, '', {positionClass: 'toast-bottom-center'});
        }
        else {
            toastr.success('增加成功', '', {positionClass: 'toast-bottom-center'});
            $('#addrecommand').modal('hide');
            window.location.reload();
        }
    }

    function init() {
        $("#add_img").fileinput({
            uploadUrl: "/common/uploadimage", // server upload action
            uploadAsync: true,
            showPreview: false,
            showUpload: false,
            allowedFileExtensions: ['jpg', 'png', 'gif'],
            maxFileCount: 5,
        }).on('fileuploaded', function (event, data, id, index) {
            var ret = data.response;
            if (0 != ret.errno) {
                toastr.error('上传失败', '', {positionClass: 'toast-bottom-center'});
            }
            //bannerImageUrl = ret.data.url;
            $("#pic").val(ret.data.url)
        }).on("filebatchselected", function (event, files) {
            $("#add_img").fileinput("upload");
        });
    }

});